package imp

import (
	sqlc "bgs/db/sqlc"
	"bgs/grpc/gen/shared/message"
	gsmsProxyGrpc "bgs/grpc/gen/util/gsms_proxy"
	statusGrpc "bgs/grpc/gen/util/status"
	"bgs/nsqp"
	"bgs/util"
	"context"
	"fmt"
	"io"

	"go.uber.org/zap"
)

// UtilService :grpc server proxy StatusOp
type UtilService struct {
	q    *sqlc.Queries
	slog *zap.SugaredLogger
	statusGrpc.StatusOpServer
	gsmsProxyGrpc.GsmsProxyOpServer
}

// NewUtilService initialization
func NewUtilService(q *sqlc.Queries, slog *zap.SugaredLogger) *UtilService {
	return &UtilService{
		q:    q,
		slog: slog,
	}
}

// NewContextLogger create a SugaredLogger with contextvalue
func (s *UtilService) NewContextLogger(ctx context.Context) *zap.SugaredLogger {
	return util.NewContextLogger(ctx, s.slog)
}

// Ping send ping sigal ,receive stream pong
func (s *UtilService) Ping(stream statusGrpc.StatusOp_PingServer) error {

	for {
		in, err := stream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		if in != nil {
			s.slog.Infof("Received: %v", in)
		}

		if err := stream.Send(&statusGrpc.PingReply{Pong: statusGrpc.PingReply_OK}); err != nil {
			return err
		}
	}
}

// SendVerifyCode 发送手机验证码
func (s *UtilService) SendVerifyCode(ctx context.Context, req *gsmsProxyGrpc.SendVerifyCodeRequest) (res *gsmsProxyGrpc.SendVerifyCodeResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("gsms_prozyImp->Create:%v", req)

	res = &gsmsProxyGrpc.SendVerifyCodeResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	requsetID := ctx.Value(util.RequestID{})
	err = nsqp.GsmsForBgapiProxy.SendVerifyCode(fmt.Sprintf("%s", requsetID), req.Phone, req.MessageType)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	return
}
